package com.jianyun.jyzs.adapter;

import android.annotation.SuppressLint;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;


import com.bumptech.glide.Glide;
import com.jianyun.jyzs.MainActivity;
import com.jianyun.jyzs.R;
import com.jianyun.jyzs.ThisApp;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.utils.LoginCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 好友Adapter实现
 */
public class ContactModuleFmAdapter extends ArrayAdapter<User> implements SectionIndexer {

    List<String> list;
    List<User> userList;
    List<User> copyUserList;
    private LayoutInflater layoutInflater;
    private SparseIntArray positionOfSection;
    private SparseIntArray sectionOfPosition;
    private int res;
    private MainActivity act;
    private DisplayImageOptions options;

    @SuppressLint("SdCardPath")
    public ContactModuleFmAdapter(MainActivity act, int resource, List<User> objects) {
        super(act, resource, objects);
        this.act = act;
        this.res = resource;
        this.userList = objects;
        initOption();
        copyUserList = new ArrayList<User>();
        copyUserList.addAll(objects);
        layoutInflater = LayoutInflater.from(act);
    }

    private void initOption() {
        options = new DisplayImageOptions.Builder()
                .showStubImage(R.drawable.default_useravatar)		// 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.default_useravatar)	// 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.default_useravatar)		// 设置图片加载或解码过程中发生错误显示的图片
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .cacheOnDisc(true)							// 设置下载的图片是否缓存在SD卡中
                .cacheInMemory(true)						// 设置下载的图片是否缓存在内存中
                .displayer(new RoundedBitmapDisplayer(5))	// 设置成圆角图片
                .build();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            if (convertView == null) {
                convertView = layoutInflater.inflate(res, null);
            }

            LinearLayout contectLinearLayout = (LinearLayout) convertView.findViewById(R.id.contectLinearLayout);
            ImageView iv_icon = (ImageView) convertView.findViewById(R.id.iv_avatar);
            TextView nameTextview = (TextView) convertView.findViewById(R.id.tv_name);
            TextView tv_phoneNum = (TextView) convertView.findViewById(R.id.tv_phoneNum);
            TextView tvHeader = (TextView) convertView.findViewById(R.id.header);
            View view_temp = (View) convertView.findViewById(R.id.view_temp);
            User user = getItem(position);
            String header = user.getHeader();
            String nameZh = user.getNameZh();
            String localIconPath = user.getLocalIconPath();
            String serverIconPath = user.getServerIconPath();
            if (position == 0 || header != null && !header.equals(getItem(position - 1).getHeader())) {
                if ("".equals(header)) {
                    tvHeader.setVisibility(View.GONE);
                    view_temp.setVisibility(View.VISIBLE);
                } else {
                    tvHeader.setVisibility(View.VISIBLE);
                    tvHeader.setText(header);
                    view_temp.setVisibility(View.GONE);
                }
            } else {
                tvHeader.setVisibility(View.GONE);
                view_temp.setVisibility(View.VISIBLE);
            }
            // 显示申请与通知item
            nameTextview.setText(nameZh);
            tv_phoneNum.setText(user.getPhoneNum() == null ? "" : user.getPhoneNum());
            iv_icon.setImageResource(R.drawable.default_useravatar);
            showUserIcon(iv_icon, localIconPath, serverIconPath);

            if (act.isSynchContact) {
                if (user.getIsCommonContact() == null || user.getIsCommonContact().intValue() == 0) {
                    contectLinearLayout.setVisibility(View.GONE);
                }
            } else {
                contectLinearLayout.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            Log.i("err","错误哦");
            e.printStackTrace();
        }
        return convertView;
    }

    @Override
    public User getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    public int getPositionForSection(int section) {
        return positionOfSection.get(section);
    }

    public int getSectionForPosition(int position) {
        return sectionOfPosition.get(position);
    }

    @Override
    public Object[] getSections() {
        positionOfSection = new SparseIntArray();
        sectionOfPosition = new SparseIntArray();
        int count = getCount();
        list = new ArrayList<String>();
        list.add(act.getString(R.string.search_header));
        positionOfSection.put(0, 0);
        sectionOfPosition.put(0, 0);
        for (int i = 1; i < count; i++) {
            String letter = getItem(i).getHeader();
            int section = list.size() - 1;
            if (list.get(section) != null && !list.get(section).equals(letter)) {
                list.add(letter);
                section++;
                positionOfSection.put(section, i);
            }
            sectionOfPosition.put(i, section);
        }
        return list.toArray(new String[list.size()]);
    }

    private void showUserIcon(ImageView iamgeView, String local, String server) {
        if (local != null && new File(local.replace("file://", "")).exists()) {
            iamgeView.setTag(local);
        } else if (server != null) {

            Glide.with(act).load(LoginCache.getInstance().getLoginCache().getErpRootUrl() + server).into(iamgeView);
        }
    }



}
